﻿using AutoMapper;
using Domain.Production_Modules;
using Infratructure.Interface;
using MediatR;
using MES.Server.API.Application.Command.Production_Modules;
using NPOI.SS.Formula.Functions;
using ReturnValue;
using Yitter.IdGenerator;

namespace MES.Server.API.Application.Handler.Production_Modules
{
    public class ProduceCreateCommandHandler : IRequestHandler<ProduceCreateCommand, ApiResult<int>>
    {
        IMapper _mapper;
        IRepository<ProduceModel> produceRep;
        public ProduceCreateCommandHandler(IMapper mapper, IRepository<ProduceModel> produceRep)
        {
            _mapper = mapper;
            this.produceRep = produceRep;
        }

        public async Task<ApiResult<int>> Handle(ProduceCreateCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result=new ApiResult<int>();
            ProduceModel produce =_mapper.Map<ProduceModel>(request);
            produce.Id = YitIdHelper.NextId();
            produce.CreateTime = DateTime.Now;
            var s1=DateTime.Now.ToString("yyyyMMdd");
            var s2=new Random().Next(100,999);
            produce.ProduceCode = s1 + s2;
            var num=await produceRep.AddAsync(produce);
            if(num>0)
            {
                result = new ApiResult<int>().AddSuccess("生产订单", num);
            }
            else
            {
                result = new ApiResult<int>().AddFail("生产订单");
            }
            result.Data = num;
            return await Task.FromResult(result);
        }
    }
}
